import { examPlanApi } from '@/api';
import type { ExamPlanListItem, ExamPlanListSearchParams } from '@/api/ExamPlan';
import useCacheColumns from '@/hooks/useCacheColumns';
import { useAppSelector } from '@/redux/store';
import { Button, message, Space, Spin } from 'antd';
import { useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import type { YmColumnsType } from 'ym-design';
import { YmTable } from 'ym-design';

//状态 100：待发布, 200 ：已发布 300：已结束 400：已过期
const EXAMSTATUSMAP = {
  100: '待发布',
  200: '已发布',
  300: '已结束',
  400: '已过期',
};

type ExamTableRecord = ExamPlanListItem;
export default function ExamPlanPage() {
  const navigator = useNavigate();
  const { entId, organizationType } = useAppSelector((state) => state.loginEnt); //organizationType 1:协会，0：企业
  const [refreshFlag, _setRefreshFlag] = useState(false);

  // 刷新table的 flag
  function refreshTable() {
    _setRefreshFlag((v) => !v);
  }

  const columns: YmColumnsType<ExamTableRecord> = useMemo(() => {
    let commonColumns: YmColumnsType<ExamTableRecord> = [
      {
        title: '计划名称',
        dataIndex: 'title',
        key: 'title',
        ellipsis: true,
        width: 240,
      },
      {
        title: '计划来源',
        dataIndex: 'source',
        key: 'source',
        render: (text) => <span>{text === 200 ? '主管部门' : '企业主体'}</span>, // 100:企业主体 200:主管部门
        width: 80,
      },
      {
        title: '计划状态',
        dataIndex: 'status',
        key: 'status',
        width: 80,
        render: (text) => <span>{EXAMSTATUSMAP[text as keyof typeof EXAMSTATUSMAP]}</span>,
      },
      {
        title: '计划开始时间',
        dataIndex: 'startTime',
        key: 'startTime',
        width: 140,
      },
      {
        title: '计划结束时间',
        dataIndex: 'endTime',
        key: 'endTime',
        width: 140,
      },
      {
        title: '操作',
        key: 'action',
        width: 100,
        fixed: 'right',
        render: (text, record) => {
          return (
            <Space direction="horizontal" size={0}>
              <Button
                type="text"
                size="small"
                disabled={record.status === 200}
                onClick={(e: React.MouseEvent) => {
                  e.stopPropagation();
                  examPlanApi
                    .deleteExamPlan({ ids: record.guid })
                    .then((res: any) => {
                      if (res.code === '200') {
                        message.success('删除成功');
                        refreshTable();
                      }
                    })
                    .catch((err) => {
                      console.log('--ExamPlan--deleteExamPlan--err--:', err);
                    });
                }}
              >
                <span className="safe-edu_table_operation_text">删除</span>
              </Button>
              <Button
                type="text"
                size="small"
                disabled={record.status !== 200}
                onClick={(e: React.MouseEvent) => {
                  e.stopPropagation();
                  examPlanApi
                    .endExamPlan(record.guid)
                    .then((res: any) => {
                      if (res.code === '200') {
                        message.success('操作成功');
                        refreshTable();
                      }
                    })
                    .catch((err) => {
                      console.log('--ExamPlan--endExamPlan--err--:', err);
                    });
                }}
              >
                <span className="safe-edu_table_operation_text">结束</span>
              </Button>
            </Space>
          );
        },
      },
    ];

    if (organizationType === 1) {
      const xiehuiColumns: YmColumnsType<ExamTableRecord> = [
        {
          title: '考试类型',
          dataIndex: 'modelType',
          key: 'modelType',
          render: (text) => <span>{text === 1 ? '常规卷' : '练习卷'}</span>,
          width: 80,
        },
        {
          title: '分类',
          dataIndex: 'className',
          key: 'className',
          width: 180,
          ellipsis: true,
        },
      ];
      commonColumns.splice(2, 0, xiehuiColumns as any);
      commonColumns = commonColumns.reduce((prev: any[], curr: any, index, array) => {
        if (Array.isArray(curr)) {
          curr.forEach((currItem: any) => {
            prev.push(currItem);
          });
        } else {
          prev.push(curr);
        }
        return prev;
      }, []);
    }
    return commonColumns;
  }, [refreshFlag, organizationType]);

  const { handleColumns, onColumnsChange, loading } = useCacheColumns({
    checkType: 23,
    columns: columns!,
  });

  return (
    <div className="safe_edu_page">
      {loading ? (
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100vh',
          }}
        >
          <Spin spinning={loading}></Spin>
        </div>
      ) : (
        <YmTable<ExamTableRecord, ExamPlanListSearchParams>
          rowKey="guid"
          columns={handleColumns}
          toolBar={{
            onColumnsChange,
            prefixNode: (
              <>
                <Button
                  type="primary"
                  onClick={() => {
                    navigator('/plannedManage/addExamPlanNew?type=add');
                  }}
                >
                  新增
                </Button>
              </>
            ),
          }}
          searchForm={{
            defaultCollapsed: true,
            span: 6,
            labelCol: { style: { width: 108 } },
            formItems: [
              {
                name: 'title',
                label: '名称',
                valueType: {
                  inputProps: {
                    autoComplete: 'off',
                  },
                },
              },
              {
                name: 'status',
                label: '计划状态',
                valueType: {
                  type: 'select',
                  selectProps: {
                    placeholder: '请选择',
                    options: [
                      { value: 200, label: '已发布' },
                      { value: 300, label: '已结束' },
                      { value: 400, label: '已过期' },
                    ],
                    showSearch: false,
                    allowClear: true,
                  },
                },
              },
            ],
          }}
          request={async ({ page }, value = {}) => {
            const result = await examPlanApi.searchExaminPlanList(
              { ...value, entId, source: organizationType === 1 ? 200 : 100 },
              page?.pageIndex,
              page?.pageSize,
            );
            return result;
          }}
          requestOptions={{
            reFreshDep: [refreshFlag],
          }}
        />
      )}
    </div>
  );
}
